package com.journey.org.ui.home.scan

import android.Manifest
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.databinding.FragmentScanBinding
import com.mvvmhabit.org.base.BaseFragment
import com.mvvmhabit.org.custom.ViewFinder
import com.mvvmhabit.org.utils.MaterialDialogUtils
import com.shouzhong.scanner.Result
import com.tbruyelle.rxpermissions2.RxPermissions

class ScanFragment : BaseFragment<FragmentScanBinding, ScanViewModel>() {

    private var vibrator: Vibrator? = null

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): Class<ScanViewModel> = ScanViewModel::class.java

    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int = R.layout.fragment_scan


    override fun initData() {
        super.initData()
        requestPermission()
    }


    // 初始化 - 身份证扫码
    private fun initScannerView() {
        // 扫描区域
        mBinding.layoutCardIdentify.setViewFinder(ViewFinder(requireContext()))
        // 是否启用身份证识别器（第二种方式），默认false
        mBinding.layoutCardIdentify.setEnableIdCard2(true)
        // 设置是否要根据扫码框的位置去调整对焦区域的位置，部分手机不支持，默认false
        mBinding.layoutCardIdentify.setShouldAdjustFocusArea(true)
        // 是否在原来识别的图像基础上旋转90度继续识别，默认false
        mBinding.layoutCardIdentify.setRotateDegree90Recognition(true)
        // 默认不保存图片false
        mBinding.layoutCardIdentify.setSaveBmp(true)
        // 启用zxing识别器
        mBinding.layoutCardIdentify.setEnableZXing(true);
        // 启用zbar识别器
        mBinding.layoutCardIdentify.setEnableZBar(true);
        // 启用银行卡识别器
        mBinding.layoutCardIdentify.setEnableBankCard(true);
        // 扫码成功后的回调
        mBinding.layoutCardIdentify.setCallback {
            startVibrator()
            println("测试数据${it.data}")
            println("测试数据${it.path}")
//            val gson = Gson()
            mViewModel?.onScanResultField?.set(it.data)
            mBinding.layoutCardIdentify.restartPreviewAfterDelay(2000);
//            when (it.type) {
//                Result.TYPE_ID_CARD_FRONT -> { // 身份证人头面
//                    if (mViewModel?.onFrontField?.get() == null) {
//                        val frontEntity: CardIdentifyFrontEntity =
//                            gson.fromJson(it.data, CardIdentifyFrontEntity::class.java)
//                        frontEntity.frontImageUrl = it.path
//                        mViewModel?.onFrontField?.set(frontEntity)
//                    }
//                    // 重新扫码
//                    mBinding.layoutCardIdentify.restartPreviewAfterDelay(2000);
//                }
//                Result.TYPE_ID_CARD_BACK -> { // 身份证国徽面
//                    if (mViewModel?.onBehindField?.get() == null) {
//                        val behindEntity =
//                            gson.fromJson(it.data, CardIdentifyBehindEntity::class.java)
//                        behindEntity.behindImageUrl = it.path
//                        mViewModel?.onBehindField?.set(behindEntity)
//                    }
//                    // 重新扫码
//                    mBinding.layoutCardIdentify.restartPreviewAfterDelay(2000);
//                }
//            }
        }
    }

    override fun onResume() {
        super.onResume()
        mBinding.layoutCardIdentify.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.layoutCardIdentify.onPause()
    }

    private fun startVibrator() {
        if (vibrator == null) {
            vibrator = ContextCompat.getSystemService(requireContext(), Vibrator::class.java)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator?.vibrate(VibrationEffect.createOneShot(300L, 20))
        } else {
            vibrator?.vibrate(300L)
        }
    }


    /**
     * 获取权限
     */
    @SuppressLint("CheckResult")
    private fun requestPermission() {
        RxPermissions(requireActivity()).request(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
        ).subscribe {
            if (!it) {
                showPermissionsDialog()
            } else {
                // 前线请求成功
                initScannerView()
            }
        }
    }

    /**
     * 显示弹框的协议
     */
    private fun showPermissionsDialog() {
        MaterialDialogUtils.showBasicDialog(requireContext(), "系统提示！", "需要授权才能使用")
            .onPositive { _, _ ->
                run {
                    requestPermission()
                }
            }
            .onNegative { _, _ ->
                run {
                    requireActivity().finish()
//                    if (!mViewModel?.isEnterMainField?.get()!!) {
//                        startActivity(MainActivity::class.java, null)
//                        finish()
//                    }
                }
            }.show()
    }


    override fun onDestroy() {
        if (vibrator != null) {
            vibrator?.cancel()
            vibrator = null
        }
        super.onDestroy()
    }
}